package net.jueb.juebCore.net.codec;

import java.nio.ByteOrder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import net.jueb.juebCore.net.message.AppMessage;
import net.jueb.juebCore.net.message.AppBuffer;

/**
 * 总长度=长度头(4)+校验位(4)+消息码(4)+消息数据body
 * 长度头值=4+4+dataLen
 * 校验位=校验位后面的所有字节计算值(code+data)
 */
public class AppMsgEncoder extends MessageToByteEncoder<AppMessage> {
	protected final Logger _log = LoggerFactory.getLogger(getClass());
	protected final static int PACK_MAX_SIZE = 64 * 1024 * 1024;
	protected final boolean validMsg;
	public static int CHECK_VALUE=0xFF;

	public AppMsgEncoder(boolean validMsg) {
		this.validMsg=validMsg;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	public void encode(ChannelHandlerContext ctx, AppMessage appMsg, ByteBuf out) throws Exception {
		ByteBuf dout = out.order(ByteOrder.LITTLE_ENDIAN);
		AppBuffer content = appMsg.getContent();
		content.reset();
		int code=appMsg.getCode();
		byte[] body=content.getBytes();
		AppBuffer validData=new AppBuffer();//需要校验的数据(消息码+数据体)
		validData.writeInt(code);//消息码
		validData.writeBytes(body);//数据体
		byte[] validDataArray=validData.getBytes();
		int validCode = 0;//4字节校验位
		if(validMsg)
		{//计算4字节校验位
			validCode = calculateCheckSum(validDataArray);
		}
		int lengthHead=4+validDataArray.length;//长度头=4字节校验位+(4字节消息码+数据长度)
		dout.writeInt(lengthHead);//4字节校验位+4字节消息码+数据长度
		dout.writeInt(validCode);//校验位
		dout.writeBytes(validDataArray);
	}
	
	private int calculateCheckSum(byte[] b) {
		int val1 = CHECK_VALUE;
		int i = 0; // 从数据byte[] 第0位开始
		int len = b.length;
		while (i < len)
		{
			val1 += b[i++] & 0xff; // byte[] 数据流
		}
		return (val1) & 0x8F8F;
	}
}
